<?php

namespace app\admin\controller\shop;

use app\admin\controller\auth\Admin;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 店铺
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\shop\Shop
     */
    protected $model = null;
    protected $subject_type = '';
    protected $week_list = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Shop;

        $subjectType = $this->model->getSubjectType();
        $this->subject_type = $subjectType;
        $week = $this->model->getWeek();
        $this->week_list = $week;
        $this->assign('subject_list',$subjectType);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['shopuser'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['shop_id','category_id','shop_name','commission_rate','createtime','username','audit_status','channel_terminal_no','channel_merchant_no']);

                $row->visible(['shopuser']);
                $row->getRelation('shopuser')->visible(['nickname','avatar','mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            //$this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            $password = input('password','');

            $admin_model = new \app\admin\model\Admin();
            if ($params) {
                Db::startTrans();
                try {

                    if (!Validate::is($password, '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $admin_params['username'] = $params['username'];
                    $admin_params['nickname'] = $params['username'];
                    $admin_params['type'] = 'shop';
                    $admin_params['salt'] = Random::alnum();
                    $admin_params['password'] = $this->auth->getEncryptPassword($password, $admin_params['salt']);
                    $admin_params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。

                    $admin_result = $admin_model->validate('Admin.add')->save($admin_params);

                    if ($admin_result === false) {
                        exception($admin_model->getError());
                    }

                    $params['admin_id'] = $admin_model->id;
                    $result = $this->model->save($params);

                    $group_data = [
                        'name'=>'Admin group',
                        'rules'=>'*',
                        'status'=>'normal',
                        'type'=>'shop',
                        'shop_id'=>$this->model->shop_id
                    ];

                    $group_model = new AuthGroup();
                    $group_model->save($group_data);

                    $dataset = ['uid' => $admin_model->id, 'group_id' => $group_model->id];
                    model('AuthGroupAccess')->save($dataset);

                    if ($result === false) {
                        $this->error($this->model->getError());
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }


    public function pass($ids = null)
    {
        $row = $this->model->get($ids);

        $row->audit_status = 2;
        $row->passtime = time();

        if ($row->save()){
            $this->success('审核通过成功');
        } else {
            $this->error('审核通过失败');
        }
    }

    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);

        $row->audit_status = 3;


        if ($row->save()){
            $this->success('拒绝成功');
        } else {
            $this->error('拒绝失败');
        }
    }

    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        $category_name = '';
        $category = \app\admin\model\shop\Category::get($row->category_id);
        $category_name = $category_name.$category->getAttr('name');

        if ($category->pid){
            $p_category = \app\admin\model\shop\Category::get($category->pid);
            $category_name = $p_category->getAttr('name').'/'.$category_name;
        }
        $this->assign('category_name',$category_name);
        $row['subject_type'] =  $this->subject_type[$row->subject_type];
        $week = explode(',',$row->work_week);
        $work_week = [];
        foreach ($week as $k=>$v){
            array_push($work_week,$this->week_list[$v]);
        }

        $this->assign('work_week',implode(',',$work_week));
        $this->assign('detail',$row);
        return $this->view->fetch();
    }

    public function bind()
    {
        $ids = input('ids',0);

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            $model = new \app\shopapi\model\lakala\ShopInfeed();

            $res = $model->bindShop($params['channel_merchant_no'],$params['channel_terminal_no'],$ids);

            $this->success('绑定成功');
        }

        $this->assign('channel_merchant_no',$row->channel_merchant_no);
        $this->assign('channel_terminal_no',$row->channel_terminal_no);
        return $this->view->fetch();
    }

    public function unbind()
    {
        $ids = input('ids',0);

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $model = new \app\shopapi\model\lakala\ShopInfeed();

        $res = $model->merchantUnbind($row->member_no,$row->channel_merchant_no,$row->channel_terminal_no);

        if ($res['code']==0){
            $this->error($res['msg']);
        }

        $this->success('成功');
    }
}
